import React, { useEffect } from 'react';
import { Outlet, useNavigate } from 'react-router-dom';
import TabBottom from './components/TabBottom';
import EventBus from './util/EventBus';
import { useToast } from './util/toast';

export default function App() {
  const toast = useToast();
  const navigate = useNavigate();
  // 每次访问子路由，都是要经过App这个函数
  // 就在这里进行判断，如果token存在，就放行，否则就阻止，然后跳转到登录
  let token = localStorage.getItem('token');
  useEffect(() => {
    if (!token) {
      // 提示
      toast('error', '请先登录');
      navigate('/login');
    }

    EventBus.on('logintimeout', () => {
      toast('error', '登录失效');
      // 把token清除
      localStorage.removeItem('token');
      // 登录失效，需要重新登录
      navigate('/login');
    });
  }, []);
  return (
    <div>
      {token ? (
        <>
          <Outlet />
          <TabBottom />
        </>
      ) : (
        <></>
      )}
    </div>
  );
}
